import { Injectable } from '@nestjs/common';

import { InjectModel } from '@nestjs/mongoose';

import { Model } from 'mongoose';

import { HDDInfoDocumentType } from '../schema/HDD/hhd_schema';

@Injectable()
export class HddService {
  constructor(
    @InjectModel('HDD_Info') private HddModel: Model<HDDInfoDocumentType>,
  ) {}

  async createHddInfo(body: any) {
    console.log('body', body);

    const hdd = new this.HddModel(body);
    return hdd.save();
  }

  async getHddInfo(query: any) {
    const { page, limit, price, order, capacity, interfaceType } = query;

    let sort = {};
    if (order) {
      sort = { price: parseInt(order) };
    } else {
      sort = {};
    }

    const filter: any = {};
    if (capacity) {
      filter.capacity = capacity;
    }
    if (interfaceType) {
      filter.interfaceType = interfaceType;
    }
    if (price) {
      if (price.min && !price.max) {
        filter.price = { $gte: price.min };
      } else if (!price.min && price.max) {
        filter.price = { $lte: price.max };
      } else if (price.min && price.max) {
        filter.price = { $gte: price.min, $lte: price.max };
      }
    }

    const result = await this.HddModel.find(filter)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort(sort)
      .exec();
    return {
      code: 200,
      msg: 'success',
      data: {
        result,
        total: await this.HddModel.countDocuments(filter),
      },
    };
  }

  async getHddInfoById(id: string) {
    const result = await this.HddModel.findById(id).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  async updateHddInfo(id: string, body: any) {
    const result = await this.HddModel.findByIdAndUpdate(id, body, {
      new: true,
    }).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  async deleteHddInfo(id: string) {
    const result = await this.HddModel.findByIdAndDelete(id).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //请求全部数据
  async getTotal() {
    const total = await this.HddModel.find().select('score price id').exec();
    return {
      code: 200,
      msg: 'success',
      data: total,
    };
  }
}
